package com.test21_常用类;

import org.junit.Test;

public class Demo02_AutoCloseable {

    @Test
    public void test1() {
        // JDK1.7之前的写法
        NetMessage message = new NetMessage();
        try {
            message.send("沐言优拓：www.yootk.com");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            message.close();
        }
    }

    @Test
    public void test2() {
        // JDK1.7之后的写法，会自动调用close方法
        try (NetMessage message = new NetMessage()) {
            message.send("沐言优拓：www.yootk.com");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

/**
 * 继承AutoCloseable接口
 */
interface IMessage extends AutoCloseable {
    public void send(String msg);
}

/**
 * 实现AutoCloseable接口，会自动调用close方法
 */
class NetMessage implements IMessage {

    public NetMessage() {
        System.out.println("【连接】创建消息的发送通道...");
    }

    @Override
    public void send(String msg) {
        if (msg.contains("yootk")) {
            throw new RuntimeException("沐言优拓：yootk.com");
        }
        System.out.println("【发送】" + msg);
    }

    @Override
    public void close() {
        System.out.println("【关闭】断开服务器连接...");
    }
}
